import React, { ReactNode, ComponentType } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';

export interface IRoute {
    path: string;
    /** 是否精准匹配 */
    exact?: boolean;
    component?: ComponentType<any>;
    redirect?: string;
    label?: string;
    icon?: string;
    isMenu?: boolean;
    children?: IRoute[];
}

interface IProps {
    routes: IRoute[];
    [propsName: string]: any;
}

const RouterView = (props: IProps) => {
    const { routes, ...extraProps } = props;

    const createComponent = (item: IRoute, Component: ComponentType<any>) => {
        return (
            <Route
                key={item.path}
                exact={true}
                path={item.path}
                render={(routeProps: any) => {
                    return (
                        <Component {...routeProps} {...extraProps} />
                    );
                }}
            />
        )
    }

    const createRoute = (item: IRoute): ReactNode => {
        if (item.redirect) {
            return (
                <Redirect
                    key={item.path}
                    exact={true}
                    path={item.path}
                    to={item.redirect}
                />
            );
        }
        if (item.children && item.children.length > 0) {
            const array = item.children.map(menu => {
                return createRoute(menu)
            });

            array.push(
                createComponent(item, item.component!)
            )
            return array
        } else {
            return (
                createComponent(item, item.component!)
            );
        }
    }

    return (
        <Switch>
            {routes.map(item => {
                return createRoute(item)
            })}
        </Switch>
    );
};

export default RouterView;
